#include "ringprogressbar.h"
#include <QPainter>
#include <QTimer>
#include<QDebug>

RingProgressBar::RingProgressBar(QWidget *parent) : QWidget(parent)
{
    rotate_angle = 0;
    percent = 0;

    timer = new QTimer(this);
    timer->stop();
    timer->setInterval(1000);
    connect(timer,&QTimer::timeout,this,
            [=]()
    {
        setPercent(percent+1);
    });

}

void RingProgressBar::slotPlayerChanged(bool)
{
    //重新开始计数
    percent = 0;
    update();

}

void RingProgressBar::newGame()
{
    percent = 0;
    timer->start();
    update();
}

void RingProgressBar::gameOver()
{
    timer->stop();
}

void RingProgressBar::setPercent(int tmp_percent)
{
    if(tmp_percent > ROUND_TIME)
    {
        timer->stop();
        emit signalTimeOut();
        return;
    }
    else
    {
        percent = tmp_percent;
        update();
    }
}

void RingProgressBar::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);

    rotate_angle = 360*percent/ROUND_TIME;

    //获取宽度和高度最小值，画出内切圆
    int side = qMin(width(), height());
    QRectF outRect(0, 0, side, side);
    QRectF inRect(20, 20, side-40, side-40);
    QString valueStr = QString("%1s").arg(QString::number(ROUND_TIME-percent));

    //画外圆
    p.setPen(Qt::NoPen);
    //快结束时进度条颜色变红
    if(ROUND_TIME - percent <= 5)
    {
        p.setBrush(QBrush(Qt::red));
    }
    else
    {
        p.setBrush(QBrush(Qt::green));
    }
    p.drawEllipse(outRect);
    p.setBrush(QBrush(Qt::gray));
    p.drawPie(outRect, (90-rotate_angle)*16, rotate_angle*16);
    //画遮罩,就是在内圈画一个圆，内外圈的间隙构成了进度条
    p.setBrush(palette().window().color());
    p.drawEllipse(inRect);
    //画文字
    QFont f = QFont("Microsoft YaHei", 15, QFont::Bold);
    p.setFont(f);
    p.setFont(f);
    p.setPen(QColor("#555555"));
    p.drawText(inRect, Qt::AlignCenter, valueStr);
}
